<template>
	<view class="content">
		<!-- 搜索框 -->
		<uni-search-bar placeholder="请输入你要搜索的内容" @confirm="search" cancelButton="none" radius="10" class="uni-searchbar"
			@clear="clearKeyword"></uni-search-bar>

		<view v-if="blogs.length != 0">
			<!-- 博客列表 -->
			<view v-for="(item, index) in blogs" :key="index" class="item-blogs" @click="toDetail(item.id)">
				<!-- 博客标题 -->
				<p class="item-title">
					<!-- 博客作者头像 -->
					<image :src="host+item.user.avatar" alt="" class="item-head" @click.stop="clickAvatar(item.user)">
					</image>

					<!-- 博客标题 -->
					<span style="border-bottom: 2px solid #8f8f94;width: 100%;">{{item.title}}</span>
					<span class="iconfont icon-xiangxia img-oper" @click.stop="popSheet(item.id)"></span>
				</p>

				<!-- 博客摘要 -->
				<p style="text-indent: 2em;">{{item.description}}</p>
				<!-- 博客分类 -->
				<p>{{item.category}}</p>
				<!-- 博客图片 -->
				<image :src="host+item.picture" mode="aspectFit" style="width: 100%;"></image>
				<p>
					<!-- 博客标签，使用 v-for 遍历标签数组 -->
					<span v-for="tag in item.tags" class="item-tag">{{tag}}</span>
				</p>
				<view class="item-icon">
					<!-- 博客点赞数 -->
					<span @click.stop="onGoods(item.id,true)" v-if="!good_ids.includes(item.id)"
						class="iconfont icon-dianzan"></span>
					<span @click.stop="onGoods(item.id,false)" v-else class="iconfont icon-liked"></span>
					<text class="item-desc">{{item.good}}</text>
					<!-- 博客评论数 -->
					<span class="iconfont icon-pinglun"></span>
					<span class="item-desc">{{item.comments.length}}</span>
					<!-- 博客阅读数 -->
					<span class="iconfont icon-view"></span>
					<span class="item-desc">{{item.readCount}}</span>
				</view>
			</view>

			<!-- 如果博客列表达到预设值 max_count，则提示已到达底部 -->
			<view v-if="blogs.length >= max_count" class="bottom">已经到达底部</view>
		</view>

		<!-- 如果博客列表为空，则提示无相关文章 -->
		<view v-else class="no-data">
			<image src="/static/icons/nodata.png" mode="widthFix" style="width: 400rpx;height: 400rpx;"></image>
			<text class="text-area">抱歉没有相关文章</text>
		</view>
		<dialog-shell title="用户信息" ref="shell" @confirm="confirmInfo">
			<view style="margin-top:40rpx; margin-bottom: 40rpx;">
				<image :src="host+user.avatar" mode="" style="height: 200rpx;width: 200rpx; border-radius: 100%;">
				</image>
				<p>昵称:{{user.nickName}}</p>
				<p>email:{{user.email}}</p>
			</view>
		</dialog-shell>
	</view>
</template>


<script>
	// 定义分页参数，当前页数为0，每页数量为3
	let page = 0;
	let size = 3;
	// 导出默认的 Vue 实例对象
	export default {
		data() {
			return {
				blogs: [], // 博客列表数据
				host: this.$params.host, // 接口地址
				good_ids: [],
				hasGood: false,
				max_count: 0,
				user: {},
			}
		},
		// 在页面加载时自动调用
		onLoad() {

			this.$notification.addNotification(this.$params.noti_refresh_count, this.notificationRefreshCount, this)
			this.$notification.addNotification(this.$params.noti_refresh_good, this.notificationRefreshGood, this)
			this.$notification.addNotification(this.$params.noti_refresh_comment, this.notificationRefreshComment, this)
			// 从本地缓存中获取博客列表、博客id列表
			let blogs = uni.getStorageSync(this.$params.key_blogs);
			let goods = uni.getStorageSync(this.$params.key_goods);
			if (!goods) {
				uni.setStorageSync(this.$params.key_goods, [])
			}
			this.maxCount()
			// 如果本地缓存中存在博客列表，则将列表存储在当前页面的blogs变量中，并更新当前博客的点赞数
			if (blogs && blogs.length != this.maxCount) {
				this.blogs = blogs
				this.good_ids = goods
			}
			// 否则从服务器请求博客列表
			else {
				this.getPageBlogs();
				this.good_ids = goods
			}

		},
		onUnload() {
			this.$notification.removeNotification(this.$params.noti_refresh_count, this)
			this.$notification.removeNotification(this.$params.noti_refresh_good, this)
			this.$notification.removeNotification(this.$params.noti_refresh_comment, this)
		},

		// 下拉刷新时自动调用
		onPullDownRefresh() {
			page = 0, // 重置当前页数为 0 
				this.blogs = [], // 清空博客列表数据
				this.getPageBlogs()
		},
		// 上拉加载时自动调用
		onReachBottom() {
			if (this.blogs.length >= this.max_count) {
				console.log("已经到达最大博客数量");
			} else {
				page = page + 1, // 当前页数 +1
					this.getPageBlogs()
			}
		},
		methods: {
			confirmInfo() {
				this.$refs.shell.clickToHide()
			},
			clickAvatar(user) {
				this.user = user
				this.$refs.shell.show()
			},
			getPageBlogs() {
				// 构造请求头
				let header = {
					"content-type": this.$params.content_type, // 内容类型
					"page": page, // 当前页数
					"size": size // 每页数量
				}
				// 发送 GET 请求获取博客列表数据
				this.$request.getWithHeader(this.host + "api/v1/blogs/page", header,
					// 成功回调函数
					res => {
						this.blogs = [...this.blogs, ...res.data]; // 拼接博客列表数据
						uni.setStorageSync(this.$params.key_blogs, this.blogs); // 将博客列表数据存储到本地缓存中
					},
					// 失败回调函数
					() => {},
					// 完成回调函数（无论成功与否都会执行）
					() => {
						uni.stopPullDownRefresh(); // 停止下拉刷新状态
					}
				)

			},
			notificationRefreshCount(info) {
				let id = info.id
				let count = info.count
				this.refreshReadCount(id, count)
			},

			notificationRefreshGood(info) {
				let id = info.id
				let index = this.blogs.findIndex(obj => obj.id === id);
				let good = info.good
				this.blogs[index].good = good
				let blog_ids = uni.getStorageSync(this.$params.key_goods)
				this.good_ids = blog_ids
				uni.setStorageSync(this.$params.key_blogs, this.blogs);
			},
			notificationRefreshComment(info) {
				console.log(info);
				let id = info.id
				let comments = info.comments
				let index = this.blogs.findIndex(obj => obj.id === id);
				this.blogs[index].comments = comments
				uni.setStorageSync(this.$params.key_blogs, this.blogs);
			},

			refreshReadCount(id, count) {
				this.blogs.forEach(b => {
					if (b.id == id) {
						b.readCount = count
					}
				})
				uni.setStorageSync(this.$params.key_blogs, this.blogs);
			},
			onGoods(id, isGood) {
				// 找到博客的索引
				let index = this.blogs.findIndex(obj => obj.id === id);
				// 设置请求头
				let header = {
					"accept": "aplication/json, */*;q=0.1",
					'Content-Type': this.$params.form_data
				};
				// 设置请求数据
				let data = {
					'id': id
				};
				// 设置请求地址
				let url = this.host + (isGood ? 'api/v1/blogs/good' : 'api/v1/blogs/delgood');
				// 发送POST请求
				this.$request.postWithHeader(url, header, data, res => {
					// 更新博客的点赞数
					this.blogs[index].good = res.data
					if (isGood) {
						// 如果是点赞操作，将博客ID添加到点赞列表中
						this.good_ids.push(id)
					} else {
						// 如果是取消点赞操作，将博客ID从点赞列表中移除
						this.$util.remove(this.good_ids, this.good_ids.indexOf(id))
					}
					// 将点赞列表和博客列表存储到本地缓存中
					uni.setStorageSync(this.$params.key_goods, this.good_ids);
					uni.setStorageSync(this.$params.key_blogs, this.blogs);
				}, () => {}, () => {})
			},

			toDetail(id) {
				uni.navigateTo({
					url: '../blog/blog?id=' + id,
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},
			search(e) {
				let kw = e.value;
				let header = {
					"content-type": this.$params.content_type, // 内容类型
				};
				if (kw.length > 0) {
					this.$request.getWithHeader(this.host + "/api/v1/blogs/search/" + kw, header,
						// 成功回调函数
						res => {
							this.blogs = [], // 清空博客列表数据
								this.blogs = res.data;
						},

						// 失败回调函数
						() => {},
						// 完成回调函数（无论成功与否都会执行）
						() => {}
					)
				}
			},
			clearKeyword() {
				let blogs = uni.getStorageSync(this.$params.key_blogs);
				// 构造请求头
				let header = {
					"content-type": this.$params.content_type, // 内容类型
				}
				// 发送 GET 请求获取博客列表数据
				this.$request.getWithHeader(this.host + "/api/v1/blogs/page", header,
					// 成功回调函数
					res => {
						if (blogs) {
							this.blogs = blogs
						}
						// 否则从服务器请求博客列表
						else {
							this.getPageBlogs();
						}
					},
					// 失败回调函数
					() => {},
					// 完成回调函数（无论成功与否都会执行）
					() => {}
				)
			},
			popSheet(id) {
				uni.showActionSheet({
					itemList: ["删除", "收藏"],
					success: res => {
						if (res.tapIndex == 0) {
							uni.showModal({
								title: '删除',
								content: '你确认删除吗',
								showCancel: true,
								cancelText: '取消',
								confirmText: '删除',
								success: res => {
									if (res.confirm) this.deleteBlog(id)
								},
								fail: () => {},
								complete: () => {}
							});
						} else if (res.tapIndex == 1) {
							uni.showToast({
								title: "已收藏"
							})
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},
			deleteBlog(id) {
				uni.showToast({
					title: "请登录"
				})
			},
			maxCount() {
				this.$request.get(this.host + 'api/v1/blogs/count', res => {
					this.max_count = res.data;
				}, () => {}, () => {})
			}
		},

	}
</script>

<style>
	@import url(index.css);
</style>